package com.fromfuture.xuhuidoc.android.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.fromfuture.xuhuidoc.android.activity.LoginActivity;
import com.fromfuture.xuhuidoc.android.activity.MyConsultRoomActivity;
import com.fromfuture.xuhuidoc.android.activity.MyConsultRoomActivityNew;
import com.fromfuture.xuhuidoc.android.activity.MyYuYueActivity;
import com.fromfuture.xuhuidoc.android.activity.mainframe.MainFrameActivity;
import com.fromfuture.xuhuidoc.android.utils.MySharedPreferencesUtils;
import com.fromfuture.xuhuidoc.cordova.plugin.MyConsultRoomPlugin;

import app.auto.runner.base.utility.ShareAlert;

/**
 * Created by hsj on 2017/8/17.
 */

public class MyWebview extends WebView {

    String tag = "MyWebView";
    Activity myActivity;
    public Handler handler = new Handler();

    public MyWebview(Context context) {
        super(context);
        init(context);
    }

    public MyWebview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    void init(Context context) {
        myActivity = (AppCompatActivity) context;

        setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e(tag, "url-->" + url);
            }

        });
        setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDatabaseEnabled(true);
        //取得缓存路径
        String path = context.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        //设置路径
        webSettings.setDatabasePath(path);
        //设置支持DomStorage
        webSettings.setDomStorageEnabled(true);
        //设置存储模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置缓存
        webSettings.setAppCacheEnabled(true);
        addJavascriptInterface(this, "android");

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) && canGoBack()) {
                    goBack();
                    return true;
                }
                return false;
            }
        });

    }


    public class MyPermission extends AppCompatActivity {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
            super.onCreate(savedInstanceState, persistentState);
            storagepermission();
        }

        //6.0动态获取权限
        public void storagepermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                    PackageManager.PERMISSION_GRANTED) {
//            new Thread(saveFileRunnable).start();
                startActivity(new Intent(this, MyConsultRoomActivityNew.class));
            } else {
                //需要申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        //如果权限允许了，则不会走下面
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case 1:
                    if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {//点击允许后走下面,只走一次
                        // 获取权限成功。操作继续。
//                    new Thread(saveFileRunnable).start();
                    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {//点击拒绝后走下面，以后只要权限未开，就每次都走这个方法
                        Toast.makeText(myActivity, "图片保存失败！" + "\n" + "贯众云医的存储权限被关闭，请在设置里打开存储权限", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //webview返回事件
    @JavascriptInterface
    public void webviewback() {
        if (canGoBack()) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    goBack();
                }
            });
        } else {
            myActivity.onBackPressed();
        }
    }

    //进入我的诊室
    @JavascriptInterface
    public void my_consult_room() {
        myActivity.startActivity(new Intent(myActivity, MyConsultRoomActivityNew.class));
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //保存病历
    @JavascriptInterface
    public void debug(String debugstr) {
        ShareAlert.shareAlert((Activity) getContext(), debugstr);
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //保存病历
    @JavascriptInterface
    public void addbli(String bli, String blimsg) {
        ((MyConsultRoomActivity) myActivity).getMyConsultRoomFragment02().sendtext(bli, blimsg);
        finish();
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //进入我的诊室
    @JavascriptInterface
    public void call(String when, String toast, String params, String command) {
        if (!TextUtils.isEmpty(command)) {
            if (command.equals("finish")) {
                ((Activity) getContext()).finish();
            }
        }
    }

    @JavascriptInterface
    public void finish() {
        ((Activity) getContext()).finish();
    }

    //我的预约
    @JavascriptInterface
    public void to_my_yuyue() {
        myActivity.startActivity(new Intent(myActivity, MyYuYueActivity.class));
    }

    //得到线上预约的条数
    @JavascriptInterface
    public void my_xsyuyue(final int num) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                MyYuYueActivity.XsyuyueNum(num);
            }
        });
    }

    //得到线下预约的条数
    @JavascriptInterface
    public void my_xxyuyue(final int num) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                MyYuYueActivity.XxyuyueNum(num);
            }
        });
    }

    //发送病例
    @JavascriptInterface
    public void docsendBl() {

    }

    @JavascriptInterface
    public void showpage(String name) {
        ((Activity) getContext()).startActivityForResult(new Intent(getContext(), BaseWebActivity.class).putExtra("name", name), 0);
    }

    //病例页面获得病例的guid，传给我的诊室碎片二以及传给病人
    @JavascriptInterface
    public void blActivityGetBlguid(String blguid) {
        MyConsultRoomPlugin.docsendBl(blguid);
    }


    //医生登录成功后，保存医生的信息  医生账户手机号,医生名称,医生guid,医生职称,医生默认头像,医生32位头像guid:
    // phone,name,guid,jobtitle,moren_tx,tx
    @JavascriptInterface
    public void savadocinfo(String phone, String name, String guid, String jobtitle, String morentx, String tx, String pwd) {
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCPHONE", phone);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCNAME", name);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCGUID", guid);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCJOBTITLE", jobtitle);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCMORETX", morentx);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCTX", tx);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCPWD", pwd);

        try {
            if (MySharedPreferencesUtils.getValue(myActivity, "ISFIRST", "HASLOGIN", "NO").equals("NO")) {
                Intent intent = new Intent(myActivity, MainFrameActivity.class);
                myActivity.startActivity(intent);
                MySharedPreferencesUtils.getValue(myActivity, "ISFIRST", "HASLOGIN", "").equals("YES");
                myActivity.finish();
            } else if (MySharedPreferencesUtils.getValue(myActivity, "ISFIRST", "HASLOGIN", "NO").equals("YES")) {
                myActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AppManager.mainFrameActivity.viewPager.setCurrentItem(0);
                        myActivity.finish();
                    }
                });
            }
        } catch (Exception e) {
            Log.d("登录错误信息", e + "");
        }

    }

    //退出登录删除医生个人信息
    @JavascriptInterface
    public void deletedocinfo() {
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCPHONE", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCNAME", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCGUID", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCJOBTITLE", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCMORETX", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCTX", null);
        MySharedPreferencesUtils.putValue(myActivity, "DOCINFO", "DOCPWD", null);
    }

    //退出登录，跳登录页面
    @JavascriptInterface
    public void exitlogin() {
        Intent intent = new Intent(myActivity, LoginActivity.class);
        myActivity.startActivity(intent);
    }

    //健康方案  创建健康方案模板
    @JavascriptInterface
    public void creathealthProgram() {
        Intent intent = new Intent(myActivity, BaseWebActivity.class);
        intent.putExtra("type", AppManager.type_creathealthProgram);
        myActivity.startActivityForResult(intent, AppManager.type_creathealthProgram);
    }

    @JavascriptInterface
    public void setTitle(String title) {
        ((BaseWebActivity) myActivity).injectTitle(title);
    }

    //注意事项 创建模板
    @JavascriptInterface
    public void creatattentionCase() {
        Intent intent = new Intent(myActivity, BaseWebActivity.class);
        intent.putExtra("type", AppManager.type_creatattentionCase);
        myActivity.startActivityForResult(intent, AppManager.type_creatattentionCase);
    }

    @JavascriptInterface
    //健康方案 编辑
    public void edithealthProgram() {
        Intent intent = new Intent(myActivity, BaseWebActivity.class);
        intent.putExtra("type", AppManager.type_edithealthProgram);
        myActivity.startActivityForResult(intent, AppManager.type_edithealthProgram);
    }

    //注意事项 编辑
    @JavascriptInterface
    public void editattentionCase() {
        Intent intent = new Intent(myActivity, BaseWebActivity.class);
        intent.putExtra("type", AppManager.type_editattentionCase);
        myActivity.startActivityForResult(intent, AppManager.type_editattentionCase);
    }

    //BaseWebActivity保存按钮 保存成功后调该方法
    @JavascriptInterface
    public void baseWebActivity_save_success_result() {
        myActivity.setResult(Activity.RESULT_OK);
        myActivity.finish();
    }

    //修改密码
    @JavascriptInterface
    public void changedPwd() {
        Intent intent = new Intent(myActivity, BaseWebActivity.class);
        intent.putExtra("type", AppManager.type_change_pwd);
        myActivity.startActivityForResult(intent, AppManager.type_change_pwd);
    }
}
